package com.dycong.common.IO.socket.SSL.ssl;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLServerSocket;
import javax.net.ssl.SSLServerSocketFactory;
import java.io.IOException;
import java.net.InetSocketAddress;

/**
 * Created by dycong on 2017/3/28.
 */
public class Server {
    private static int PORT=12121;
    private SSLContext sslContext;
    private SSLServerSocket sslServerSocket=null;
    public Server(){}
    public Server(int port){
        PORT=port;
    }
    public void start(){
        try {
            if (sslServerSocket!=null){
                synchronized (Server.class){
                    if (sslServerSocket!=null){
                        sslContext=ServerAuth.getSSLContext();
                        SSLServerSocketFactory sslServerSocketFactory=sslContext.getServerSocketFactory();
                        //只是创建一个TCP连接，SSL handshake还没开始
                        //客户端或服务端第一次试图获取socket输入流或输出流时，
                        //SSL handshake才会开始
                        SSLServerSocket sslServerSocket=(SSLServerSocket) sslServerSocketFactory.createServerSocket();

                        String[] pwdsuits = sslServerSocket.getSupportedCipherSuites();
                        sslServerSocket.setEnabledCipherSuites(pwdsuits);

                        //todo 默认是client mode，必须在握手开始之前调用
                        sslServerSocket.setUseClientMode(false);

                        //只有设置为server mode，该配置才生效
                        //todo 如果客户端不提供其证书，通信将会结束
                        sslServerSocket.setNeedClientAuth(true);
                        //只有设置为server mode，该配置才生效
                        //即使客户端不提供其证书，通信也将继续
//                        sslServerSocket.setWantClientAuth(true);

                        sslServerSocket.bind(new InetSocketAddress(PORT));
                    }
                }
            }

        }catch (Exception e){

        }finally {
            try {
                if (sslServerSocket!=null){
                    sslServerSocket.close();
                }
            }catch (IOException e){

            }
        }
    }
}
